package std

import (
	"database/sql"
	"fmt"
	"strconv"

	"rdbmsx/config"

	"github.com/ClickHouse/clickhouse-go/v2"
)

func CompressOpenDB() error {
	env := config.ClickHouseConfig.Option()
	conn := clickhouse.OpenDB(&env)

	defer func() {
		conn.Exec("DROP TABLE example")
	}()
	conn.Exec("DROP TABLE IF EXISTS example")

	if _, err := conn.Exec(`
		CREATE TABLE example (
			  Col1 Array(String)
			, Col2 UInt64
		) Engine Memory
		`); err != nil {
		return err
	}

	scope, err := conn.Begin()
	if err != nil {
		return err
	}

	batch, err := scope.Prepare("INSERT INTO example")
	if err != nil {
		return err
	}

	for i := 0; i < 1000; i++ {
		if _, err := batch.Exec(
			[]string{strconv.Itoa(i), strconv.Itoa(i + 1), strconv.Itoa(i + 2), strconv.Itoa(i + 3)},
			uint64(i),
		); err != nil {
			return err
		}
	}

	if err := scope.Commit(); err != nil {
		return err
	}

	return nil
}

func CompressOpen() error {
	// note compress=gzip&compress_level=5
	conn, err := sql.Open("clickhouse", fmt.Sprintf("http://%s?username=%s&password=%s&compress=gzip&compress_level=5", config.ClickHouseHost, config.ClickHouseUser, config.ClickHousePassword))
	if err != nil {
		return err
	}

	defer func() {
		conn.Exec("DROP TABLE example")
	}()
	conn.Exec("DROP TABLE IF EXISTS example")

	if _, err := conn.Exec(`
		CREATE TABLE example (
			  Col1 Array(String)
			, Col2 UInt64
		) Engine Memory
		`); err != nil {
		return err
	}

	scope, err := conn.Begin()
	if err != nil {
		return err
	}

	batch, err := scope.Prepare("INSERT INTO example")
	if err != nil {
		return err
	}

	for i := 0; i < 1000; i++ {
		if _, err := batch.Exec(
			[]string{strconv.Itoa(i), strconv.Itoa(i + 1), strconv.Itoa(i + 2), strconv.Itoa(i + 3)},
			uint64(i),
		); err != nil {
			return err
		}
	}

	if err := scope.Commit(); err != nil {
		return err
	}

	return nil
}
